﻿package  {

	public class vector2 {
		public var x:Number,y:Number;
		public function vector2(xx:Number,yy:Number) {
			// constructor code
			x=xx;
			y=yy;
		}
		public function add(rt:vector2):vector2
		{
			return new vector2(x+rt.x,y+rt.y);
		}
		public function sub(rt:vector2):vector2
		{
			return new vector2(x-rt.x,y-rt.y);
		}
		public function mulf(f:Number):vector2
		{
			return new vector2(x*f,y*f);
		}
		public function length()
		{
			return Math.sqrt(x*x+y*y);
		}
		public function getdegree()
		{
			if(x==0 && y==0)return 0;
			return Math.atan2(y,x)*180/Math.PI;

		}
		public function formdegree(dr:Number)
		{
			while(dr>180)dr=dr-180;
			while(dr<-180)dr=dr+180;
			//trace("dd",dr);
			if(dr==90)
			{
				x=0;y=-1;
				return;
			}
			if(dr==-90)
			{
				x=0;y=1;
				return;
			}
			var a:Number=Math.tan(dr*Math.PI/180);
			//trace("a",a);
			x=1/Math.sqrt(a*a+1);
			y=a*x;
			if(dr>90 || dr<-90)
			{
				x=-x;
				y=-y;
			}
			//trace("dr:",x,y);
		}
		public function normalize():vector2
		{
			var nnl:Number;
			nnl=this.length();
			var vv:vector2=new vector2(this.x,this.y);
			if(nnl>0)
			{
				 nnl = 1.0 / nnl;
                vv.x *= nnl;
                vv.y *= nnl;
			}
			return vv;
		}
		public function crossProduct(  rkVector:vector2 ):Number
        {
            return x * rkVector.y - y * rkVector.x;
        }
		public static function v2intersect(p1:vector2,p2:vector2,s1:vector2,s2:vector2)
		{
			/*trace(p1.x,p1.y);
			trace(p2.x,p2.y);
			trace(s1.x,s1.y);
			trace(s2.x,s2.y);*/
			var pn:vector2=p2.sub(p1).normalize();
			var sn:vector2=s2.sub(s1).normalize();
			var s:Number;
			var t:Number;
			var c:vector2=s1.sub(p1);
			s=(c.x*pn.y-pn.x*c.y);
			s=s/(pn.crossProduct(sn));
			t=((c.y)+s*sn.y)/pn.y;
			/*trace("s",s,"t",t);
			var hitp1:vector2;
			var hitp2:vector2;
			hitp1=p1.add(pn.mulf(t));
			hitp2=s1.add(sn.mulf(s));
			trace(hitp1.x,hitp1.y);
			trace(hitp2.x,hitp2.y);*/
			if(s>0 && t>0 && t<p2.sub(p1).length() && s<s2.sub(s1).length())
			{
				return true;
			}
			return false;
		}
	}
	
}
